package com.jurassic.demo.service;

import com.jurassic.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

/**
 * @Author pan_jin
 * @Description: $
 * @Date: 2022/7/11 20:24
 * @Version: 1.0.0
 * @Slogan: 梦想还是要有的万一实现了呢
 */
//@Component
public class UserService {
    @Autowired
    MailServiceTwo mailService;

//    @Autowired
//    JdbcTemplate jdbcTemplate;

    public void setMailService(MailServiceTwo mailService) {
        this.mailService = mailService;
    }

    private List<User> users = Arrays.asList(// users:
            new User(1, "bob@example.com", "password", "Bob"), // bob
            new User(2, "alice@example.com", "password", "Alice"), // alice
            new User(3, "tom@example.com", "password", "Tom")
    );

    public User login(String email, String password) {
        for (User user : users) {
            if (user.getEmail().equalsIgnoreCase(email) && user.getPassword().equals(password)) {
                mailService.sendLoginMail(user);
                return user;
            }
        }
        throw new RuntimeException("login failed.");
    }

    public User getUser(long id) {
        return  users.stream().filter(user -> user.getId()==id).findFirst().get();
//        return users.stream().filter(user -> user.getId() == id).findFirst().orElseThrow();
    }

    public User register(String email, String password, String name) {
        users.forEach((user) -> {
            if (user.getEmail().equalsIgnoreCase(email)) {
                throw new RuntimeException("email exist.");
            }
        });
        User user = new User(users.stream().mapToInt(u -> u.getId()).max().getAsInt() + 1, email, password, name);
        users.add(user);
        mailService.sendRegistrationMail(user);
        return user;
    }
}
